package com.xuxk.project.util;


import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DateUtil {
	

	/**
	 * 设置一天中最大小时数
	 * */
	public static int HOUR_OF_DAY_MAX = 24;
	
	/**
	 * 上午上班时间从8点30分起算
	 */
	public static int WORK_TIME_AM_START = 830;
	
	/**
	 * 上午下班时间从12点10分起算
	 */
	public static int WORK_TIME_AM_END = 1210;
	
	
	/**
	 * 下午上班时间从14点算
	 */
	public static int WORK_TIME_PM_START = 1400;
	
	/**
	 * 下午下班时间从18点算(因需求调整为19：00)
	 */
	public static int WORK_TIME_PM_END = 1900;

	/**
	 *  年月日格式
	 */
	public static String YMD = "yyyyMMdd";
	 /**
     * 把毫秒转化成日期
     * @param millSec(毫秒数)
     * @return
     */
    public static Date transferLongToDate(Long millSec){


     Date date= new Date(millSec);

     return date ;

    }
	
	/**
	 * 比较第一日期是不是第二个日期之后的某天
	 * @param srcDay  
	 * @param comparedDay
	 * @return
	 */
	public static boolean afterDay(Date srcDay,Date comparedDay){
		boolean flag = false;
		if(srcDay!=null&&srcDay!=null){
			if(srcDay.after(comparedDay)){
				if(!DateUtils.isSameDay(srcDay, comparedDay)){
					flag = true;
				}
			}
		}
		return flag;
	}

	/**
	 * 判断传入日期的时间是否为工作时间
	 * @param date
	 * @return
	 */
	public static boolean isWorkTime(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		int hours = calendar.get(Calendar.HOUR_OF_DAY);
		int min = calendar.get(Calendar.MINUTE);
		
		//需求调整为8：30 ~ 19：00 为上班时间 ,19:00 ~ 8:30 为非上班时间
		if((hours*100+min) <=WORK_TIME_PM_END  && (hours*100+min) >= WORK_TIME_AM_START){
			return true;
		}

		return false;
	}
	
	private static boolean isAmWorkTime(int time){

		return time <= WORK_TIME_AM_END && time >= WORK_TIME_AM_START;
	}
	
	private static boolean isPmWorkTime(int time){

		return time <= WORK_TIME_PM_END && time >= WORK_TIME_PM_START;
	}
	
	
	public static int getDayOfWeek(Date date){
		if(null == date){
			return -1;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.get(Calendar.DAY_OF_WEEK);
	}
	
	/**
	 * 判断指定的日期是否在选中的星期内
	 * @param date
	 * @param weeks
	 * @return
	 */
	public static boolean isInDayOfWeek(Date date, int[] weeks){
		if(null == date || null == weeks){
			return false;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int week = calendar.get(Calendar.DAY_OF_WEEK);
		for(int i : weeks){
			if(i == week){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断指定的日期是否在选中的星期内
	 * @param date
	 * @param weeks
	 * @return
	 */
	public static boolean isInDayOfWeek(Date date, String[] weeks){
		if(null == date || null == weeks){
			return false;
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		String week = (calendar.get(Calendar.DAY_OF_WEEK)-1)+"";
		for(String i : weeks){
			if(i.equals(week)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 某天是否是  工作日
	 */
	public static boolean isWorkday(Date date){
		boolean flag = false;
		if(date!=null){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int week = calendar.get(Calendar.DAY_OF_WEEK);
			switch (week) {
			case Calendar.SUNDAY:
			case Calendar.MONDAY:
			case Calendar.TUESDAY:
			case Calendar.WEDNESDAY:
			case Calendar.THURSDAY:
				flag = true;
				break;
			}
		}
		return flag;
	}
	/**
	 * 某天是否是双休日
	 */
	public static boolean isWeekends(Date date){
		boolean flag = false;
		if(date!=null){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int week = calendar.get(Calendar.DAY_OF_WEEK);
			switch (week) {
			case Calendar.FRIDAY:
			case Calendar.SATURDAY:
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	/**
	 * 判断某天是工作日(因业务需求，以周六和周日为周末)
	 * @param date
	 * @return
	 */
	public static boolean isWeekend(Date date){
		boolean flag = false;
		if(date !=null){
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int week = calendar.get(Calendar.DAY_OF_WEEK);
			switch (week) {
			case Calendar.SATURDAY:
			case Calendar.SUNDAY:
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	
	/**
	 * 获取到当天时间 并
	 * 把时分秒  毫秒位都置为0
	 * @return
	 */
	public static Date getTodayRemoveTime(){
		Calendar today = Calendar.getInstance();
		today.set(Calendar.HOUR_OF_DAY, 0);
		today.set(Calendar.MINUTE, 0);
		today.set(Calendar.SECOND, 0);
		today.set(Calendar.MILLISECOND, 0);
		return today.getTime();
	}
	/**
	 * 去除掉date中的时分秒 和毫秒数 为0
	 * @param date
	 * @return
	 */
	public static Date removeTime(Date date){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		
		return c.getTime();
	}
	
	/**
	 * 得到当月的第一天并去除掉date中的时分秒 和毫秒数 为0
	 * @param date
	 * @return
	 */
	public static Date removeMonthTime(Date date){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.DAY_OF_MONTH, 1);  
		//将小时至0  
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		
		return c.getTime();
	}
	
	/**
	 * 将一天当中的时分秒设置为时(23)分(59)秒(59)；
	 * @param date
	 * @return
	 */
	public static Date getTodayMaxTime(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		calendar.setTime(date);
    	//设置时
    	calendar.set(Calendar.HOUR_OF_DAY, 23); 
    	//设置分
    	calendar.set(Calendar.MINUTE,59); 
    	calendar.set(Calendar.SECOND, 59);
		
		return calendar.getTime();
	}
	/**
	 * 去除掉date中的时分秒 和毫秒数 为0
	 * @param field 查询类型  @see {@link Calendar}  支持间隔秒数Calendar.SECOND，分数Calendar.MINUTE，小时数Calendar.HOUR，天数Calendar.DATE，周数Calendar.WEEK_OF_YEAR，月数Calendar.MONTH,年数Calendar.YEAR，默认返回天数
	 * @param date
	 * @return
	 */
	public static Date removeTimeByfield(Date date,int field){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		
		switch (field) {
			case Calendar.HOUR_OF_DAY:
				c.set(Calendar.HOUR_OF_DAY, 0);
			case Calendar.MINUTE:
				c.set(Calendar.MINUTE, 0);
			case Calendar.SECOND:
				c.set(Calendar.SECOND, 0);
			case Calendar.MILLISECOND:
				c.set(Calendar.MILLISECOND, 0);
			default:
				 
				break ;
			
		}
		
		return c.getTime();
	}
	
	/**
	 * 去除掉date中的时分秒 和毫秒数 为0 且获取倒推指定天数后的日期对象
	 * @param date
	 * @return
	 */
	public static Date removeTime(Date date, int beforeDays){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		
		int inputDayOfYear = c.get(Calendar.DAY_OF_YEAR);
		c.set(Calendar.DAY_OF_YEAR , inputDayOfYear-beforeDays);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		
		return c.getTime();
	}
	/**
	 * 
	 * @param startDate	起始时间
	 * @param field	时间类型	秒Calendar.SECOND，分Calendar.MINUTE，小时Calendar.HOUR，天Calendar.DATE，周Calendar.WEEK_OF_YEAR，月Calendar.MONTH,年Calendar.YEAR 
	 * @param times 时间间隔数
	 * @return 设定时间间隔，返回某个日期
	 */
	public static Date getDateByCalendar(Date startDate,int field,int times){
		if(startDate!=null){
			Calendar start = Calendar.getInstance();
			start.setTime(startDate) ;
			start.add(field, times) ;
			startDate  = start.getTime() ;
		}
		return startDate ;
	}
	/**
	 * 时间间隔 查询
	 * @param date1 起始日期
	 * @param date2 终止日期
	 * @param field 查询类型  @see {@link Calendar}  支持间隔秒数Calendar.SECOND，分钟Calendar.MINUTE，小时数Calendar.HOUR，天数Calendar.DATE，周数Calendar.WEEK_OF_YEAR，月数Calendar.MONTH,年数Calendar.YEAR，默认返回天数
	 * @return  间隔数
	 */
	public static int DaysInterval(Date date1,Date date2,int field){
		if(date1!=null&&date2!=null){
			Calendar start = Calendar.getInstance();
			Calendar end = Calendar.getInstance();
			if(date1.before(date2)){
				start.setTime(date1);
				end.setTime(date2);
			}else{
				start.setTime(date2);
				end.setTime(date1);
			}
			
			long interval = end.getTimeInMillis()-start.getTimeInMillis();
			switch (field) {
			case Calendar.SECOND:
				return (int)(interval/1000);
			case Calendar.MINUTE:
				return (int)(interval/60000);
			case Calendar.HOUR:
				return (int)(interval/3600000);
			case Calendar.WEEK_OF_YEAR:
				return (int)(interval/604800000);
			case Calendar.MONTH:
				return (end.get(Calendar.MONTH)-start.get(Calendar.MONTH))+(end.get(Calendar.YEAR)-start.get(Calendar.YEAR))*12;
			case Calendar.YEAR:
				return end.get(Calendar.YEAR) - start.get(Calendar.YEAR);
			default:
				return (int)(interval/86400000);
			}
		}
		return 0;
	}
	/**
	 * 返回指定格式的日期
	 * 
	 * @param date
	 * @param format
	 * @return
	 */
	public static String getDate(Date date, String format) {
		if (date == null) {
			return "";
		}
		SimpleDateFormat sdFormat = new SimpleDateFormat(format);

		return sdFormat.format(date);
	}
	
	/**
	 * 返回指定格式的日期
	 * @param date
	 * @param format
	 * @return
	 * @throws ParseException 
	 */
	public static Date formatDate(Date date, String format) throws ParseException {
		if (date == null) {
			return null;
		}
		SimpleDateFormat sdFormat = new SimpleDateFormat(format);
		return sdFormat.parse(sdFormat.format(date));
	}
	
	/**
	 * 返回指定格式的日期
	 * 
	 * @param strDate
	 * @param format
	 * @return
	 * @throws ParseException 
	 */
	public static Date getDate(String strDate, String format) throws ParseException {
		if (strDate == "") {
			return null;
		}
		SimpleDateFormat sdFormat = new SimpleDateFormat(format);
		return sdFormat.parse(strDate);
	}
	/**
	 * 比较日期
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static boolean isDateBefore(Date date1,Date date2){
		return date1.before(date2);
	}
	/**
	 * 日期加1天
	 * @param date
	 * @return
	 */
	public static Date dateAdd(Date date,int dd){
		Calendar cal = Calendar.getInstance();	
		cal.setTime(date); 
		cal.add(Calendar.DAY_OF_YEAR, dd);
		return cal.getTime();
	}
	
	/**
	 * 将时间  08：01   转换成日期 ：yyyy-MM-dd HH:mm:ss
	 * @param date
	 * @return
	 */
	public static Date getDateByTime(Date date,String time){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		String str[] = time.split(":");
		c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str[0]));
		c.set(Calendar.MINUTE, Integer.parseInt(str[1]));
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}
   public static String getWeekOfDate1(Date dt) {
	   String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
	   Calendar cal = Calendar.getInstance();
	   cal.setTime(dt);
	   int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
	   if (w < 0){
		   w = 0;
	   }
	   return weekDays[w];
   }

   /**
    * 
    * @param startTime
    * @param endTime
    * @param field 查询类型：默认-返回天数;小时数-Calendar.HOUR;
    * @return  返回两个时间点整除天数后的小时差或者天数
    * */
   public static int getSubTime(Date startTime, Date endTime,int field){
	   int times  = 0 ;
	   if(startTime != null && endTime != null ){
		   times =  DaysInterval(startTime,endTime,Calendar.HOUR);
		   if(field == Calendar.HOUR ){	//小时
			   if( times >= 24  ){
				   times = times % HOUR_OF_DAY_MAX ;
			   }
		   }else if(field == Calendar.DATE ){//天

			   times = times / HOUR_OF_DAY_MAX;
		   }
	   }
	   return times ;
	   
   }


	public static String fmtTodayToSix() {
		Calendar calendar = Calendar.getInstance();
		String yy = String.valueOf(calendar.get(Calendar.YEAR) % 100);
		if (yy.length() == 1) {
			yy = "0" + yy;
		}
		String mm = String.valueOf(calendar.get(Calendar.MONTH)+1);
		if (mm.length() == 1) {
			mm = "0" + mm;
		}
		String dd = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
		if(dd.length() == 1){
			dd = "0" + dd;
		}
		return yy + mm + dd;
	}
	
	public static String showDay(int hours){
		if(hours <=0 ){
			return "0";
		}
		
		return hours/HOUR_OF_DAY_MAX + "天" + hours%HOUR_OF_DAY_MAX + "小时";
	}
	
	public static void main(String[] args) throws Exception {
		Date s = getDate("2018-04-10 15:15:50", "yyyy-MM-dd HH:mm:ss");
		Date e = getDate("2018-04-10 15:18:20", "yyyy-MM-dd HH:mm:ss");
		
		System.out.println(getDate(removeTimeByfield(s,Calendar.MILLISECOND), "yyyy-MM-dd HH:mm:ss"));
	}
	/**
	 * 校验时间格式是否为指定的格式，并且是否是正确的时间：例如：2007/02/29 就会报错
	 * @param str
	 * @param format
	 * @return
	 */
	public static boolean isValidDate(String str,String format) {
	      boolean convertSuccess=true;
	      
	       SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
	       try {
	    	   // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
	    	   simpleDateFormat.setLenient(false);
	    	   simpleDateFormat.parse(str);
	       } catch (ParseException e) {
	           e.printStackTrace();
	    	   // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
	           convertSuccess=false;
	       } 
	       return convertSuccess;
	}
	
	/**
	 * 根据两时间字符串获取时差，字符串类型都是HH：mm，并判断是否是第二天
	 * @param time1
	 * @param time2
	 * @return map(存放是否是第二天的判断，航班飞行时间)
	 */
	public static Map<String,String> getJetLag(String time1,String time2){
		Map<String,String> map = new HashMap<String,String>();
		String[] time1Split = time1.split(":");
		String[] time2Split = time2.split(":");
		if(time1Split.length==2 && time2Split.length==2){
			int time1Num =Integer.valueOf(time1Split[0])*60+Integer.valueOf(time1Split[1]);
			int time2Num =Integer.valueOf(time2Split[0])*60+Integer.valueOf(time2Split[1]);
			int jetLagNum;
			if(time1Num-time2Num<0){
				map.put("istoday", "true");
				jetLagNum = time2Num-time1Num;
			}else{
				map.put("istoday", "false");
				jetLagNum = time2Num+24*60-time1Num;
			}
			String jetLag = ((Integer)(jetLagNum/60)).toString()+"小时"+((Integer)(jetLagNum%60)).toString()+"分";
			map.put("jetLag", jetLag);
		}
		return map;
	}
	/**
	 * 根据出生日期，计算年龄
	 */
	public static int getAge(Date birthDay,Date nowDate){
		int age = 0 ;
		
		if(null == birthDay ) {
			return  age  ;
		}
		
		Calendar cal = Calendar.getInstance();  
		cal.setTime(nowDate);
		
        if (cal.before(birthDay)) {  
            throw new IllegalArgumentException(  
                    "The birthDay is before Now.It's unbelievable!");  
        }  
        int yearNow = cal.get(Calendar.YEAR);  
        int monthNow = cal.get(Calendar.MONTH);  
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);  
        cal.setTime(birthDay);  
  
        int yearBirth = cal.get(Calendar.YEAR);  
        int monthBirth = cal.get(Calendar.MONTH);  
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);  
  
        age = yearNow - yearBirth;  
  
        if (monthNow <= monthBirth) {  
            if (monthNow == monthBirth) {  
                if (dayOfMonthNow < dayOfMonthBirth){
                	age--;
				}
            }else{  
                age--;  
            }  
        }  
        return age;  
	}
	
	/**
	 * 前后移动日期
	 * @param date
	 * @param move -1:向前移动一天，1:向后移动一天
	 * @return
	 */
	public static Date moveDate(Date date,int move){
		
		 Calendar calendar = new GregorianCalendar();
		 calendar.setTime(date);
		 calendar.add(Calendar.DATE,move);//把日期往后增加一天.整数往后推,负数往前移动
		 return calendar.getTime(); //这个时间就是日期移动之后的时间
		
	}

	/**
	 * 仅限产品 预定天数
	 * 获取产品定制所需天数
	 * @param begin
	 * @param end
	 * @return
	 */
	public static int calcuteDayCount(Date begin,Date end){
		if(begin!=null&&end!=null){
			return (int)Math.ceil((end.getTime()-begin.getTime())/86400000)+1;
		}
		return 0;
	}

	public static Date currentTime(){
		Calendar calendar = Calendar.getInstance() ;
		return calendar.getTime() ;
	}

	// 获得当前月--开始日期
	public static Date getMinMonthDate(Date date) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,
				calendar.getActualMinimum(Calendar.DAY_OF_MONTH));

		return  calendar.getTime() ;
	}

	// 获得当前月--结束日期
	public static Date getMaxMonthDate(Date date){
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_MONTH,
				calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return  calendar.getTime();

	}
}